import Cookie from "js-cookie";

export function createA(href, target) {
    var a = document.createElement("a");
    a.setAttribute("href", href);
    a.setAttribute("target", target || "_blank");
    a.setAttribute("id", "startTelMedicine");
    // 防止反复添加
    if (document.getElementById("startTelMedicine")) {
        document.body.removeChild(document.getElementById("startTelMedicine"));
    }
    document.body.appendChild(a);
    a.click();
}

export function getUrlParamNative(n,str) {
    var e, r;
    var _str=str||location.search||location.hash.substring("1",location.hash.length)
    if(!_str||location.hash){
        var index11=location.hash.indexOf("?")
        _str=location.hash.substring(index11,location.hash.length)
    }
    console.log("getUrlParamNative _str",_str)
    return r = new RegExp("(^|&)" + n + "=([^&]*)(&|$)"), e = _str.substr(1).match(r), null !== e ? decodeURI(e[2]) : null
};

export function safeParseJson(str) {
    try {
        return JSON.parse(str)
    } catch (e) {
        return null
        console.error('转换json失败', str)

    }
}

export function uuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

export function copy2bang(value) {
    // for ie
    if (window.clipboardData) {
        window.clipboardData.clearData();
        window.clipboardData.setData('text', value);
    }
// for modern browser
    else if (document.execCommand) {
        var element = document.createElement('pre');
        element.textContent = value;
        document.body.appendChild(element);
        if (document.selection) {
            var range = document.body.createTextRange();
            range.moveToElementText(element);
            range.select();
        } else if (window.getSelection) {
            var range = document.createRange();
            range.selectNode(element);
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(range);
        }
        document.execCommand('copy');
        element.remove ? element.remove() : element.removeNode(true);
    }
}

// 下划线转换驼峰
export function toHump(name) {
    return name.replace(/\_(\w)/g, function (all, letter) {
        return letter.toUpperCase();
    });
}

// 驼峰转换下划线
export function toLine(name) {
    return name.replace(/([A-Z])/g, "_$1").toLowerCase();
}


export function firstworldupp(s) {
    return s[0].toUpperCase() + s.slice(1);
}

export function firstworlddown(s) {
    return s[0].toLowerCase() + s.slice(1);
}

export function getCookie(key) {
    var result = Cookie.get(key) || "";
    return result;
}

export function setCookie(
    key,
    value,
    option = {
        time: 2
    }
) {
    Cookie.set(key, value, {expires: option.time / 24});
}